package com.neuedu.mblog.controller;

import com.neuedu.mblog.dao.UploadFileDao;
import com.neuedu.mblog.entiry.UploadFile;
import com.neuedu.mblog.framework.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.*;

/**
 * 项目：his
 * 创建时间：  2021/12/15   14:57
 * 作者 :jshand
 * 描述 : 上传文件的Controlle
 */
@WebServlet(urlPatterns = "/servlet_upload")
@MultipartConfig
public class ServletUploadController extends HttpServlet {

    private UploadFileDao dao = new UploadFileDao();

    /**
     * //        Collection<Part> parts = request.getParts();
     * //        for (Part part : parts) {
     * //            part.getName();
     * //            part.getSize();
     * //            part.getSubmittedFileName();
     * //            InputStream ios = part.getInputStream();
     * //        }
     *
     * @param request
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        UploadFile uploadFile = new UploadFile();

        String username = request.getParameter("username");
        Part uploadPart = request.getPart("upload");

        String fileName = uploadPart.getSubmittedFileName();
        //保存到数据库中
        uploadFile.setOriginName(fileName);
        String ext = fileName.substring(fileName.lastIndexOf("."));
        //UUID
        uploadFile.setPath(UUID.randomUUID().toString()+ext);
        uploadFile.setSize(uploadPart.getSize());
        uploadFile.setIp(request.getRemoteAddr());


        //将浏览器的IO数据写到硬盘中
       writeToDisk(uploadPart,uploadFile);

        //插入
        dao.save(uploadFile);

        //跳转到列表页
        resp.sendRedirect(request.getContextPath()+"/file?_type=list");

    }

    /**
     * 将文件写到硬盘
     * @param uploadPart
     * @param uploadFile
     * @throws IOException
     */
    private void writeToDisk(Part uploadPart,UploadFile uploadFile) throws IOException {
        //将文件流转储到硬盘中
        //从浏览器读
        InputStream is = uploadPart.getInputStream();
        //写到硬盘中  Constants.UPLOAD_BASE_DIR上传文件的基础路径
        OutputStream os = new FileOutputStream(new File(Constants.UPLOAD_BASE_DIR,uploadFile.getPath()));
        //从文件中读取，写到浏览器
        byte[] bts = new byte[1024];
        int len = -1;
        while (   ( len =  is.read(bts) )  != -1        ){
            os.write(bts,0,len);
        }
        //关闭资源
        os.close();
        is.close();
    }





}
